﻿using System;
using System.Data.Entity;
using MvcTests.BestPractice.Core;

namespace MvcTests.BestPractice.Repository.EntityFramework
{
    public class EntityFrameworkContext:IEntityFrameworkContext
    {
        private readonly BookLibraryDbContext _context;

        public DbContext DbContext => _context;

        public EntityFrameworkContext(BookLibraryDbContext context)
        {
            _context = context;
        }

        public bool Committed { get; private set; }
        public void Commit()
        {
            if (!Committed)
            {
                _context.SaveChanges();
                Committed = true;
            }
        }

        public void Rollback()
        {
            Committed = false;

        }

        public void RegisterNew<TAggregateRoot>(TAggregateRoot obj) 
            where TAggregateRoot : class, IAggregateRoot
        {
            _context.Set<TAggregateRoot>().Add(obj);
            Committed = false;

        }

        public void RegisterModified<TAggregateRoot>(TAggregateRoot obj)
            where TAggregateRoot : class, IAggregateRoot
        {
            _context.Entry(obj).State = EntityState.Modified;
            Committed = false;
        }

        public void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj)
            where TAggregateRoot : class, IAggregateRoot
        {
            _context.Set<TAggregateRoot>().Remove(obj);
            Committed = false;
        }


        public void Dispose()
        {
            _context.Dispose();
        }
    }
}